package com.clt.ess.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.clt.ess.base.Constant;
import com.clt.ess.dao.SecretMapper;
import com.clt.ess.gjzw.domain.*;
import com.clt.ess.gjzw.domain.applyRandom.ApplyRandomRequest;
import com.clt.ess.gjzw.domain.applyRandom.ApplyRandomResponse;
import com.clt.ess.gjzw.domain.applySealCode.ApplySealCodeRequest;
import com.clt.ess.gjzw.domain.applySealCode.ApplySealCodeResponse;
import com.clt.ess.gjzw.domain.confirmReceipt.ConfirmReceiptRequest;
import com.clt.ess.gjzw.domain.confirmReceipt.ConfirmReceiptRequestData;
import com.clt.ess.gjzw.domain.confirmReceipt.ConfirmReceiptResponse;
import com.clt.ess.gjzw.domain.confirmReceipt.ConfirmReceiptResponseData;
import com.clt.ess.gjzw.domain.revocationSealInfo.*;
import com.clt.ess.gjzw.domain.updateProtectKey.*;
import com.clt.ess.gjzw.domain.uploadRecordInfos.*;
import com.clt.ess.service.IGjzwService;
import com.clt.ess.gjzw.utils.*;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.util.encoders.Hex;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.clt.ess.base.GJZWConstant.*;
import static com.clt.ess.gjzw.utils.CypherUtil.signValueG;
import static com.clt.ess.utils.StringUtils.*;


@Service
public class GjzwServiceImpl implements IGjzwService {

    @Autowired
    private SecretMapper secretMapper;

//    private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * 获取唯一赋码(电子印章制作)
     * @param applicantCert 平台证书
     * @param areaCode 区划代码
     * @return 唯一赋码
     */
    public String getSealCode(String applicantCert, String areaCode) {
        //首先获取服务端随机数
        String randomA = getRandom16();
        ApplyRandomRequest randomRequest = new ApplyRandomRequest();
        randomRequest.setApplicantCert(applicantCert);
        randomRequest.setRandomA(randomA);
        //调用接口，获取响应对象B
        String randomB = getRandomNum(randomRequest);
        if (randomB == null) {
            //返回结果错误
            return null;
        }
        //
        ApplySealCodeRequest sealCodeRequest = new ApplySealCodeRequest();
        //组织随机数组合
        sealCodeRequest.setTokenInfo(randomA + randomB);
        //填入行政区划代码
        sealCodeRequest.setData(new AreaNumData(areaCode));
        //执行获取统一赋码国家政务平台接口方法
        ApplySealCodeResponse applySealCodeResponse = applySealCode(sealCodeRequest);
        //接受到
        if (applySealCodeResponse!=null){
            //返回统一赋码
            return  applySealCodeResponse.getData().getSealCode();
        }
        return null;
    }

    /**
     * 上传备案信息接口(电子印章制作)
     * @param applicantCert 平台证书
     * @param data 印章信息
     * @return 任务id
     */
    @Override
    public TaskNumData uploadRecordInfosGetTaskId(String applicantCert, List<UploadRecordInfosRequestData> data) {
        //取到随机数
        String randomA = getRandom16();
        //获取服务端随机数
        ApplyRandomRequest randomRequest = new ApplyRandomRequest();
        randomRequest.setApplicantCert(applicantCert);
        randomRequest.setRandomA(randomA);
        String randomB = getRandomNum(randomRequest);
        if (randomB == null ) {
            return null;
        }
        //组织印章备案请求参数bean
        UploadRecordInfosRequest uploadRecordInfosRequest = new UploadRecordInfosRequest();
        uploadRecordInfosRequest.setTokenInfo(randomA + randomB);
        uploadRecordInfosRequest.setData(data);

        UploadRecordInfosResponse uploadRecordInfosResponse = uploadRecordInfo(uploadRecordInfosRequest);
        if (uploadRecordInfosResponse == null ) {
            return null;
        }
        return uploadRecordInfosResponse.getData();
    }

    /**
     * 查询并下载公安下发数据(电子印章制作)
     * @param taskNumData
     * @return
     */
    public FilePackage uploadRecordInfoCheckResult(TaskNumData taskNumData) {
        UploadRecordInfosCheckResultRequest uploadRecordInfosCheckResultRequest = new UploadRecordInfosCheckResultRequest();
        uploadRecordInfosCheckResultRequest.setData(taskNumData);

        FilePackage filePackage = uploadRecordInfoCheckResult(uploadRecordInfosCheckResultRequest);
        if (filePackage == null) {
            return null;
        }
        return filePackage;
    }

    /**
     * 发送回执(电子印章制作)
     *
     * @param applicantCert
     * @param data
     * @return
     */
    @Override
    public String confirmReceiptRequest(String applicantCert, List<ConfirmReceiptRequestData> data) {
        String randomA = getRandom16();
        ApplyRandomRequest randomRequest = new ApplyRandomRequest();

        randomRequest.setApplicantCert(applicantCert);
        randomRequest.setRandomA(randomA);
        String randomB = getRandomNum(randomRequest);
        if (randomB == null) {
            //返回结果错误
            return null;
        }

        ConfirmReceiptRequest confirmReceiptRequest = new ConfirmReceiptRequest();

        confirmReceiptRequest.setTokenInfo(randomA + randomB);

        confirmReceiptRequest.setData(data);

        String yzbm = confirmReceipt(confirmReceiptRequest);
        if (yzbm == null ) {
            return null;
        }
        return yzbm;
    }

    /**
     * 上传电子印章撤销信息(电子印章撤销)
     *
     * @param applicantCert
     * @param data
     * @return
     */
    public TaskNumData revocationSealInfo(String applicantCert, List<RevocationSealInfoRequestData> data) {
        String randomA = getRandom16();
        ApplyRandomRequest randomRequest = new ApplyRandomRequest();
        randomRequest.setApplicantCert(applicantCert);
        randomRequest.setRandomA(randomA);
        String randomB = getRandomNum(randomRequest);
        if (randomB == null) {
            //返回结果错误
            return null;
        }
        RevocationSealInfoRequest revocationSealInfoRequest = new RevocationSealInfoRequest();
        revocationSealInfoRequest.setTokenInfo(randomA + randomB);
        revocationSealInfoRequest.setData(data);
        RevocationSealInfoResponse revocationSealInfoResponse = revocationSealInfo(revocationSealInfoRequest);
        if (revocationSealInfoResponse == null || revocationSealInfoResponse.getResultCode() == null || !"0".equals(revocationSealInfoResponse.getResultCode())) {
            return null;
        }
        return revocationSealInfoResponse.getData();
    }

    /**
     * 业务服务：查询结果(电子印章撤销)
     *
     * @param data
     * @return
     */
    public String revocationSealInfoCheckResult(TaskNumData data) {

        RevocationSealInfoCheckResultRequest revocationSealInfoCheckResultRequest = new RevocationSealInfoCheckResultRequest();

        revocationSealInfoCheckResultRequest.setData(data);

        String yzbm = revocationSealInfoCheckResult(revocationSealInfoCheckResultRequest);
        if (yzbm == null) {
            return null;
        }
        return yzbm;
    }

    /**
     * 上传保护密钥更新信息(电子印章更新)
     *
     * @param applicantCert
     * @param data
     * @return
     */
    public TaskNumData updateProtectKey(String applicantCert, List<UpdateProtectKeyRequestData> data) {
        String randomA = getRandom16();
        ApplyRandomRequest randomRequest = new ApplyRandomRequest();
        randomRequest.setApplicantCert(applicantCert);
        randomRequest.setRandomA(randomA);
        String randomB = getRandomNum(randomRequest);
        if (randomB == null) {
            //返回结果错误
            return null;
        }
        UpdateProtectKeyRequest updateProtectKeyRequest = new UpdateProtectKeyRequest();

        updateProtectKeyRequest.setTokenInfo(randomA + randomB);
        updateProtectKeyRequest.setData(data);
        UpdateProtectKeyResponse updateProtectKeyResponse = updateProtectKey(updateProtectKeyRequest);
        if (updateProtectKeyResponse == null || updateProtectKeyResponse.getResultCode() == null || !"0".equals(updateProtectKeyResponse.getResultCode())) {
            return null;
        }
        return updateProtectKeyResponse.getData();
    }

    /**
     * 业务服务：查询结果(电子印章更新)
     *
     * @param data
     * @return
     */
    public FilePackage updateProtectKeyCheckResult(TaskNumData data) {
        UpdateProtectKeyCheckResultRequest updateProtectKeyCheckResultRequest = new UpdateProtectKeyCheckResultRequest();

        updateProtectKeyCheckResultRequest.setData(data);

        FilePackage filePackage = updateProtectKeyCheckResult(updateProtectKeyCheckResultRequest);
        if (filePackage == null ) {
            return null;
        }
        return filePackage;
    }


    /**
     * 获取随机数协议接口
     *
     * @param request
     * @return
     * @Date 2019/06/30
     */
    public String getRandomNum(ApplyRandomRequest request) {
        request.setTaskCode("applyRandom");
        request.setVersion("1.0");
        //测试环境
        RvSecret rvSecret = secretMapper.getSecret(applyRandom_INTERFACE);
        String jsonString = gjzwPostWithJson(rvSecret, request.toString());
        ApplyRandomResponse applyRandomResponse = FastJsonUtils.jsonToBean(jsonString, ApplyRandomResponse.class);
        if ("0".equals(applyRandomResponse.getResultCode())) {
            return applyRandomResponse.getRandomB();
        }
        return null;
    }
    /**
     * 上传备案信息接口的请求业务
     * @param request 参数bean
     * @return  响应bean
     */
    public UploadRecordInfosResponse uploadRecordInfo(UploadRecordInfosRequest request) {
        request.setTaskCode("uploadRecordInfos");
        request.setVersion("1.0");
        //0 表示备案业务，1 表示保护密钥更新业务，2 表示印章撤销，3 表示申请电子印章唯一赋码业务
        request.setTaskTypeCode("0");
        //处理信息进行签名
        SignInfo info = null;
        info = signValueG(request.toString().getBytes(StandardCharsets.UTF_8));
        request.setSignInfo(info);
        //测试环境
        RvSecret rvSecret = secretMapper.getSecret(uploadRecordInfos_INTERFACE);
        //正式环境
//        RvSecret rvSecret = secretMapper.getSecret("F002t1710012");
        String jsonString = gjzwPostWithJson(rvSecret, request.toString());
        if (jsonString == null){
            return null;
        }
        JSONObject jsonObject = FastJsonUtils.jsonToJsonBean(jsonString);
        //组织响应bean
        UploadRecordInfosResponse uploadRecordInfosResponse = new UploadRecordInfosResponse();
        uploadRecordInfosResponse.setTaskCode(jsonObject.getString("taskCode"));
        uploadRecordInfosResponse.setVersion(jsonObject.getString("version"));
        uploadRecordInfosResponse.setTaskTypeCode(jsonObject.getString("taskTypeCode"));
        uploadRecordInfosResponse.setResultCode(jsonObject.getString("resultCode"));
        uploadRecordInfosResponse.setResultCodeMsg(jsonObject.getString("resultCodeMsg"));

        TaskNumData taskNumData = FastJsonUtils.jsonToBean(jsonObject.getString("data"),TaskNumData.class);
        uploadRecordInfosResponse.setData(taskNumData);

        SignInfo signInfo = FastJsonUtils.jsonToBean(jsonObject.getString("signInfo"),SignInfo.class);
        uploadRecordInfosResponse.setSignInfo(signInfo);

        if ("0".equals(uploadRecordInfosResponse.getResultCode())) {
            return uploadRecordInfosResponse;
        }
        return null;
    }

    /**
     * 上传备案信息接口查询并下载公安下发数据接口（处理package对象）
     *
     * @param request
     * @return
     * @Date 2019/06/30
     */
    public FilePackage uploadRecordInfoCheckResult(UploadRecordInfosCheckResultRequest request) {
        request.setTaskCode("checkResult");
        request.setVersion("1.0");
        request.setTaskTypeCode("0");
        //处理信息进行签名
        SignInfo info = null;
        info = signValueG(request.toString().getBytes(StandardCharsets.UTF_8));
        request.setSignInfo(info);
        //测试环境
        RvSecret rvSecret = secretMapper.getSecret(checkResult_INTERFACE);
        //正式环境
//        RvSecret rvSecret = secretMapper.getSecret("F002t1710017");
        String jsonString = gjzwPostWithJson(rvSecret, request.toString());
        if (jsonString==null){
            return null;
        }
        //组装响应bean
        JSONObject jsonObject = FastJsonUtils.jsonToJsonBean(jsonString);
        UploadRecordInfosCheckResultResponse uploadRecordInfosCheckResultResponse = new UploadRecordInfosCheckResultResponse();
        uploadRecordInfosCheckResultResponse.setTaskCode(jsonObject.getString("taskCode"));
        uploadRecordInfosCheckResultResponse.setVersion(jsonObject.getString("version"));
        uploadRecordInfosCheckResultResponse.setResultCode(jsonObject.getString("resultCode"));
        uploadRecordInfosCheckResultResponse.setResultCodeMsg(jsonObject.getString("resultCodeMsg"));
        uploadRecordInfosCheckResultResponse.setTaskTypeCode(jsonObject.getString("taskTypeCode"));
        //取文件
        Map map1 = jsonObject.toJavaObject(Map.class);
        String data = map1.get("data").toString();
        if (data!=null) {
            Pattern p = Pattern.compile("\\[|\\]");
            Matcher m = p.matcher(data);
            data = m.replaceAll("");
        }
        JSON json2 = FastJsonUtils.jsonToBean(data,JSON.class);
        Map map2 = json2.toJavaObject(Map.class);
        if (!"0".equals(map2.get("errorCode"))){
            return null;
        }
        String aPackage = map2.get("package").toString();

//        uploadRecordInfosCheckResultResponse.setData(fileDataList);

        SignInfo signInfo = FastJsonUtils.jsonToBean(jsonObject.getString("signInfo"),SignInfo.class);
        uploadRecordInfosCheckResultResponse.setSignInfo(signInfo);


        if ("0".equals(uploadRecordInfosCheckResultResponse.getResultCode())) {
            return FastJsonUtils.jsonToBean(aPackage, FilePackage.class);
        }
        return null;
    }

    /**
     * 上传保护密钥更新信息接口
     *
     * @param request
     * @return
     * @Date 2019/06/30
     */
    public UpdateProtectKeyResponse updateProtectKey(UpdateProtectKeyRequest request)  {
        request.setTaskCode("updateProtectKey");
        request.setVersion("1.0");
        request.setTaskTypeCode("1");
        //处理信息进行签名
        SignInfo info = null;
        info = signValueG(request.toString().getBytes(StandardCharsets.UTF_8));
        request.setSignInfo(info);
        //测试环境
//        RvSecret rvSecret = secretMapper.getSecret("F002t1710010");
        //正式环境
        RvSecret rvSecret = secretMapper.getSecret(updateProtectKey_INTERFACE);
        String jsonString = gjzwPostWithJson(rvSecret, request.toString());



        if (jsonString != null) {
            return FastJsonUtils.jsonToBean(jsonString, UpdateProtectKeyResponse.class);
        }
        return null;


    }

    /**
     * 上传保护密钥更新信息接口查询并下载公安下发数据接口（处理package）
     *
     * @param request
     * @return
     * @Date 2019/06/30
     */
    public FilePackage updateProtectKeyCheckResult(UpdateProtectKeyCheckResultRequest request) {
        request.setTaskCode("checkResult");
        request.setVersion("1.0");
        request.setTaskTypeCode("1");
        //处理信息进行签名
        SignInfo info = null;
        info = signValueG(request.toString().getBytes(StandardCharsets.UTF_8));
        request.setSignInfo(info);

        RvSecret rvSecret = secretMapper.getSecret(checkResult_INTERFACE);
        String jsonString = gjzwPostWithJson(rvSecret, request.toString());

        if (jsonString==null){
            return null;
        }
        //组装响应bean
        JSONObject jsonObject = FastJsonUtils.jsonToJsonBean(jsonString);
        UpdateProtectKeyCheckResultResponse uploadRecordInfosCheckResultResponse = new UpdateProtectKeyCheckResultResponse();
        uploadRecordInfosCheckResultResponse.setTaskCode(jsonObject.getString("taskCode"));
        uploadRecordInfosCheckResultResponse.setVersion(jsonObject.getString("version"));
        uploadRecordInfosCheckResultResponse.setResultCode(jsonObject.getString("resultCode"));
        uploadRecordInfosCheckResultResponse.setResultCodeMsg(jsonObject.getString("resultCodeMsg"));
        uploadRecordInfosCheckResultResponse.setTaskTypeCode(jsonObject.getString("taskTypeCode"));
        //取文件
        Map map1 = jsonObject.toJavaObject(Map.class);
        String data = map1.get("data").toString();
        if (data!=null) {
            Pattern p = Pattern.compile("\\[|\\]");
            Matcher m = p.matcher(data);
            data = m.replaceAll("");
        }
        JSON json2 = FastJsonUtils.jsonToBean(data,JSON.class);
        Map map2 = json2.toJavaObject(Map.class);
        if (!"0".equals(map2.get("errorCode"))){
            return null;
        }
        String aPackage = map2.get("package").toString();

//        uploadRecordInfosCheckResultResponse.setData(fileDataList);

        SignInfo signInfo = FastJsonUtils.jsonToBean(jsonObject.getString("signInfo"),SignInfo.class);
        uploadRecordInfosCheckResultResponse.setSignInfo(signInfo);


        if ("0".equals(uploadRecordInfosCheckResultResponse.getResultCode())) {
            return FastJsonUtils.jsonToBean(aPackage, FilePackage.class);
        }

        return null;

    }

    /**
     * 上传电子印章撤销信息接口
     *
     * @param request
     * @return
     * @Date 2019/06/30
     */
    public RevocationSealInfoResponse revocationSealInfo(RevocationSealInfoRequest request) {
        request.setTaskCode("revocationSealInfo");
        request.setVersion("1.0");
        request.setTaskTypeCode("2");
        //处理信息进行签名
        SignInfo info = null;
        info = signValueG(request.toString().getBytes(StandardCharsets.UTF_8));
        request.setSignInfo(info);
        //测试环境
//        RvSecret rvSecret = secretMapper.getSecret("F002t1710011");
        //正式环境
        RvSecret rvSecret = secretMapper.getSecret(revocationSealInfo_INTERFACE);
        String jsonString = gjzwPostWithJson(rvSecret, request.toString());
        if (jsonString != null) {
            return null;
        }
        JSONObject jsonObject = FastJsonUtils.jsonToJsonBean(jsonString);

        RevocationSealInfoResponse revocationSealInfoResponse = new RevocationSealInfoResponse();
        revocationSealInfoResponse.setTaskCode(jsonObject.getString("taskCode"));
        revocationSealInfoResponse.setVersion(jsonObject.getString("version"));
        revocationSealInfoResponse.setResultCode(jsonObject.getString("resultCode"));
        revocationSealInfoResponse.setResultCodeMsg(jsonObject.getString("resultCodeMsg"));
        revocationSealInfoResponse.setTaskTypeCode(jsonObject.getString("taskTypeCode"));


        SignInfo signInfo = FastJsonUtils.jsonToBean(jsonObject.getString("signInfo"),SignInfo.class);
        revocationSealInfoResponse.setSignInfo(signInfo);


        revocationSealInfoResponse.setData(FastJsonUtils.jsonToBean(jsonObject.getString("data"), TaskNumData.class));

        if ("0".equals(revocationSealInfoResponse.getResultCode())) {
            return revocationSealInfoResponse;
        }

        return null;
    }

    /**
     * 上传电子印章撤销信息接口查询并下载公安下发数据接口
     *
     * @param request
     * @return
     * @Date 2019/06/30
     */
    public String revocationSealInfoCheckResult(RevocationSealInfoCheckResultRequest request) {
        request.setTaskCode("checkResult");
        request.setVersion("1.0");
        request.setTaskTypeCode("2");

        //处理信息进行签名
        SignInfo info = null;
        info = signValueG(request.toString().getBytes(StandardCharsets.UTF_8));
        request.setSignInfo(info);

        //测试环境
//        RvSecret rvSecret = secretMapper.getSecret("F002t1710009");
        //正式环境
        RvSecret rvSecret = secretMapper.getSecret(checkResult_INTERFACE);
        String jsonString = gjzwPostWithJson(rvSecret, request.toString());

        if (jsonString ==null){
            return null;
        }
        JSONObject jsonObject = FastJsonUtils.jsonToJsonBean(jsonString);

        RevocationSealInfoCheckResultResponse revocationSealInfoCheckResultResponse = new RevocationSealInfoCheckResultResponse();
        revocationSealInfoCheckResultResponse.setTaskCode(jsonObject.getString("taskCode"));
        revocationSealInfoCheckResultResponse.setVersion(jsonObject.getString("version"));
        revocationSealInfoCheckResultResponse.setResultCode(jsonObject.getString("resultCode"));
        revocationSealInfoCheckResultResponse.setResultCodeMsg(jsonObject.getString("resultCodeMsg"));
        revocationSealInfoCheckResultResponse.setTaskTypeCode(jsonObject.getString("taskTypeCode"));


        SignInfo signInfo = FastJsonUtils.jsonToBean(jsonObject.getString("signInfo"),SignInfo.class);
        revocationSealInfoCheckResultResponse.setSignInfo(signInfo);

        //取文件
        Map map1 = jsonObject.toJavaObject(Map.class);
        String data = map1.get("data").toString();
        if (data!=null) {
            Pattern p = Pattern.compile("\\[|\\]");
            Matcher m = p.matcher(data);
            data = m.replaceAll("");
        }
        JSON json2 = FastJsonUtils.jsonToBean(data,JSON.class);
        Map map2 = json2.toJavaObject(Map.class);
        if (!"0".equals(map2.get("errorCode"))){
            return null;
        }
        String yzmb = map2.get("yzmb").toString();

        if ("0".equals(revocationSealInfoCheckResultResponse.getResultCode())) {
            return yzmb;
        }

        return null;
    }

    /**
     * 申请电子印章唯一赋码接口
     *
     * @param request
     * @return
     * @Date 2019/06/30
     */
    public ApplySealCodeResponse applySealCode(ApplySealCodeRequest request) {

        request.setTaskCode("applySealCode");
        request.setVersion("1.0");
        request.setTaskTypeCode("3");
        //处理信息进行签名
        SignInfo info;
        info = signValueG(request.toString().getBytes(StandardCharsets.UTF_8));
        request.setSignInfo(info);
        //访问接口
        //测试环境
        RvSecret rvSecret = secretMapper.getSecret(applySealCode_INTERFACE);
        //正式环境
//        RvSecret rvSecret = secretMapper.getSecret("F002t1710014");
        String jsonString = gjzwPostWithJson(rvSecret, request.toString());

        //组装响应bean
        JSONObject jsonObject = FastJsonUtils.jsonToJsonBean(jsonString);
        ApplySealCodeResponse applySealCodeResponse = new ApplySealCodeResponse();
        applySealCodeResponse.setTaskCode(jsonObject.getString("taskCode"));
        applySealCodeResponse.setVersion(jsonObject.getString("version"));
        applySealCodeResponse.setTaskTypeCode(jsonObject.getString("taskTypeCode"));
        applySealCodeResponse.setResultCode(jsonObject.getString("resultCode"));
        applySealCodeResponse.setResultCodeMsg(jsonObject.getString("resultCodeMsg"));

        SealCodeData sealCodeData = FastJsonUtils.jsonToBean(jsonObject.getString("data"),SealCodeData.class);
        applySealCodeResponse.setData(sealCodeData);

        SignInfo signInfo = FastJsonUtils.jsonToBean(jsonObject.getString("signInfo"),SignInfo.class);
        applySealCodeResponse.setSignInfo(signInfo);

        if ("0".equals(applySealCodeResponse.getResultCode())) {
            return applySealCodeResponse;
        }
        return null;
    }

    /**
     * 提交确认回执接口
     * @param request
     * @return
     * @Date 2019/06/30
     */
    public String confirmReceipt(ConfirmReceiptRequest request) {
        request.setTaskCode("confirmReceipt");
        request.setVersion("1.0");
        request.setTaskTypeCode("0");
        //处理信息进行签名
        SignInfo info = null;
        info = signValueG(request.toString().getBytes(StandardCharsets.UTF_8));
        request.setSignInfo(info);
        //测试环境和正式环境一致
        RvSecret rvSecret = secretMapper.getSecret(confirmReceipt_INTERFACE);

        String jsonString = gjzwPostWithJson(rvSecret, request.toString());
        if (jsonString ==null){
            return null;
        }
        //组装响应bean
        JSONObject jsonObject = FastJsonUtils.jsonToJsonBean(jsonString);
        ConfirmReceiptResponse confirmReceiptResponse = new ConfirmReceiptResponse();
        confirmReceiptResponse.setTaskCode(jsonObject.getString("taskCode"));
        confirmReceiptResponse.setVersion(jsonObject.getString("version"));
        confirmReceiptResponse.setTaskTypeCode(jsonObject.getString("taskTypeCode"));
        confirmReceiptResponse.setResultCode(jsonObject.getString("resultCode"));
        confirmReceiptResponse.setResultCodeMsg(jsonObject.getString("resultCodeMsg"));

//        SealCodeData sealCodeData = FastJsonUtils.jsonToBean(jsonObject.getString("data"),SealCodeData.class);
//        confirmReceiptResponse.setData(sealCodeData);
        //取文件
        Map map1 = jsonObject.toJavaObject(Map.class);
        String data = map1.get("data").toString();
        if (data!=null) {
            Pattern p = Pattern.compile("\\[|\\]");
            Matcher m = p.matcher(data);
            data = m.replaceAll("");
        }
        JSON json2 = FastJsonUtils.jsonToBean(data,JSON.class);
        Map map2 = json2.toJavaObject(Map.class);
        if (!"0".equals(map2.get("errorCode"))){
            return null;
        }
        String yzbm = map2.get("yzbm").toString();

        SignInfo signInfo = FastJsonUtils.jsonToBean(jsonObject.getString("signInfo"),SignInfo.class);
        confirmReceiptResponse.setSignInfo(signInfo);

        return yzbm;
    }

    /**
     * 国家政务平台电子印章系统请求方法
     *
     * @param rvSecret Secret 对象
     * @param json  请求been类
     * @return 请求返回的json字符串
     */
    public String gjzwPostWithJson(RvSecret rvSecret, String json) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        if (rvSecret.getAppKey()!=null){
            rvSecret.setAppKey(getDecryptString(rvSecret.getAppKey()));
        }
        if (rvSecret.getSecret()!=null){
            rvSecret.setSecret(getDecryptString(rvSecret.getSecret()));
        }
        if (rvSecret.getUserName()!=null){
            rvSecret.setUserName(getDecryptString(rvSecret.getUserName()));
        }

        if (rvSecret.getPassword()!=null){
            rvSecret.setPassword(getDecryptString(rvSecret.getPassword()));
        }
        HttpPost httppost = new HttpPost(fileFilingUrl + rvSecret.getInterfaceCode() + "/1");
        //appkey
        String appKey = rvSecret.getAppKey();
        //租户账号
        String username = rvSecret.getUserName();
        //请求唯一号
        String nonce = UUID.randomUUID().toString();
        //请求创建时间
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String created = sdf.format(new Date());

        String secret = rvSecret.getSecret();
        secret = nonce + "_" + created + "_" + secret;
        byte[] md = new byte[32];
        byte[] psw = secret.getBytes();
        SM3Digest sm3 = new SM3Digest();
        sm3.update(psw, 0, psw.length);
        sm3.doFinal(md, 0);
        //生成密码摘要
        String passwdDigest = new String(Hex.encode(md));

        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("App_key", appKey));//应用标识
        formparams.add(new BasicNameValuePair("Username", username));//租户帐号
        formparams.add(new BasicNameValuePair("Nonce", nonce));//请求唯一号，随机字符串
        formparams.add(new BasicNameValuePair("Created", created));//请求创建时间
        formparams.add(new BasicNameValuePair("PasswdDigest", passwdDigest));//密码摘要SM3(nonce + "_" + created + "_" + secret)
        formparams.add(new BasicNameValuePair("parameter", json));
        try {
            System.out.println("---------------------------------");
            System.out.println("fasongcanshu"+new String(json.getBytes(StandardCharsets.UTF_8),"GBK"));
            System.out.println("---------------------------------");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);

            CloseableHttpResponse response = httpClient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity, "UTF-8");
//                    JSONObject jsonObject = FastJsonUtils.jsonToJsonBean(result);
                    Map map = FastJsonUtils.jsonToBean(result, Map.class);
                    System.out.println("---------------------------------");
                    System.out.println("fanhuijieguo"+new String(JSON.toJSONString(map.get("data"))
                            .getBytes(StandardCharsets.UTF_8),"GBK"));
                    System.out.println("---------------------------------");
                    if ("10".equals(map.get("code").toString())) {
                        Map map1 = FastJsonUtils.jsonToBean(map.get("data").toString(), Map.class);
                        if ("0".equals(map1.get("code").toString())) {
                            return JSON.toJSONString(map1.get("data"));
                        }else{
                            return null;
                        }
                    } else {
                        return null;
                    }


                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
